// pages/createIssue/createIssue.js
const app = getApp();
const path = app.globalData.path;
var loginFlag = wx.getStorageSync('token');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    title: '',
    path: [],
    imgs: [],
    upload_picture_list: [],
    issueSourceList: null,
    programList: null,
    vehicleList: null,
    productTypeList: null,
    issueLevelList: null,
    issueTypeList: null,
    processStatus: 'DRAFT',
    list: '',
    reportOrg: '',
    reportOrgName: '',
    reportBy: '',
    selectedUser: '',
    selectedUserId: '',
    date: '',
    sourceId: ''

  },

  // 预览图片
  previewImg(e) {
    console.log(e);
    //获取当前图片的下标
    let index = e.currentTarget.dataset.index;
    console.log(index);
    console.log(this.data.picList);
    //所有图片
    let imgs = this.data.picList;
    var imgPaths = [];
    for (var i = 0; i < imgs.length; i++) {
      imgPaths.push(imgs[i].path);
      console.log(imgPaths);
    }
    wx.previewImage({
      //当前显示图片
      current: imgs[index].path,
      //所有图片
      urls: imgPaths
    })
  },

  findWithAttr: function(array, attr, value) {
    for (var i = 0; i < array.length; i += 1) {
      if (array[i][attr] === value) {
        return i;
      }
    }
    return -1;
  },

  getIssueInfo: function(issueId) {
    var that = this;
    var loginFlag = wx.getStorageSync('token');

  },
  getIssueTypeList: function() {
    var that = this;
    var loginFlag = wx.getStorageSync('token');

  },
  getIssueLevelList: function() {
    var that = this;
    var loginFlag = wx.getStorageSync('token');

  },

  getProgramList: function() {
    var that = this;
    var loginFlag = wx.getStorageSync('token');

  },

  getIssueSourceList: function() {
    var that = this;
    var loginFlag = wx.getStorageSync('token');

  },

  getIssueTitle: function(result, loginFlag, that) {
    // 根据问题信息已返回的结果 
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueSourceList.action',
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      success: function(response) {

        var sourceList = JSON.parse(response.data);
        var sourceArray = sourceList.data;
        var issueSourceId = result.data.issueSourceId; // 获取问题信息返回结果中的 issueSourceId

        for (var i = 0; i < sourceArray.length; i++) {
          if (issueSourceId == sourceArray[i].id) {
            that.setData({
              issueSourceTitle: sourceArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  getIssueTypeTitle: function(result, loginFlag, that) {
    var that = this;
    // var path = getApp().path;
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueTypeList.action',
      //发送的数据
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      //成功回调
      success: function(res) {

        var issueType = JSON.parse(res.data);
        var issueTypeArray = issueType.data;
        var issueTypeId = result.data.issueTypeId;

        for (var i = 0; i < issueTypeArray.length; i++) {
          if (issueTypeId == issueTypeArray[i].id) {
            that.setData({
              issueTypeTitle: issueTypeArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  getPartTypeName: function(result, loginFlag, that) {

    // 根据问题信息已返回的结果productTypes作为参数 再发送一个request .
    wx.request({
      url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',

      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        productTypes: result.data.productTypes
      },
      success: function(r) {
        // console.log(r.data);
        var pmPartTypes = JSON.parse(r.data);

        // 从返回的数据中找到 问题信息 中对应的零件类别  
        // that.setData({
        //   productTypeList: pmPartTypes.data
        // })

        var partArray = pmPartTypes.data;
        var issuePartTypeId = result.data.partTypeId; // 获取问题返回结果中的 partTypeId

        for (var i = 0; i < partArray.length; i++) {
          if (issuePartTypeId == partArray[i].id) {
            that.setData({
              partTypeName: partArray[i].name
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  // 删除按钮先reset  然后删除问题
  formreset: function(e) {
    var that = this;
    console.log(e);
    var loginFlag = wx.getStorageSync('token');
    if (loginFlag) {
      wx.showLoading({

      })
      wx.request({
        url: path + '/wx-issue/q-iissue!removeIssue.action',
        header: {
          'token': loginFlag
        },
        data: {
          issueId: that.data.sourceId
        },
        dataType: "JSON",
        success: function(res) {

          var result = JSON.parse(res.data);

          that.setData({
            sourceId: ''
          })
          wx.showToast({
            title: '已删除',
            duration: 1500
          })
          wx.switchTab({
            url: '../issueList/issueList'
          })
        },
        fail: function(res) {
          console.log(res);
        }
      })
    }

  },
  uploadpic: function(e) {
    //   console.log(that.data.sourceId);
    var that = this;
    let pic_list = that.data.picList;
    let imgs = that.data.imgs
    var uploadUrl = path + 'wx-com/image!uploadCmImage.action'
    let loginFlag = wx.getStorageSync('token');
    wx.chooseImage({
      count: 8, // 默认9，这里显示一次选择相册的图片数量 
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
        // console.log(res);
        var tempFiles = res.tempFiles
        //把选择的图片 添加到集合里
        for (let i in tempFiles) {
          tempFiles[i]['upload_percent'] = 0
          tempFiles[i]['path_server'] = ''
          imgs.push(tempFiles[i].path);
          //  console.log(imgs);
          //upload_file_server(uploadUrl,that,tempFiles,that.data.sourceId,i,loginFlag)
          wx.showLoading({
            title: '正在上传....',
          })
          wx.uploadFile({
            // 模拟https
            url: uploadUrl, //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
            filePath: tempFiles[i].path, //上传的文件本地地址    
            name: 'upload',
            header: {
              'token': loginFlag
            },
            formData: {
              'num': i,
              'source': 'QIM_ISSUE_IMAGE',
              'sourceId': that.data.issueInfo.id // 注意这里 要穿 issueInfo 的id  其他页面也一样 看你把id 存到了哪个变量
            },
            //附近数据，这里为路径     
            success: function(res) {
              //   console.log(res);
              var result = JSON.parse(res.data);
              //   console.log(result);
              tempFiles[i].imageId = result.data.id;
              // //字符串转化为JSON  
              console.log("--------------");
              //   console.log(tempFiles);
              pic_list.push(tempFiles[i])
              // if (data.Success == true) {
              //   var filename = data.file //存储地址 显示
              //   tempFiles[i]['path_server'] = filename
              // } else {
              //   tempFiles[i]['path_server'] = filename
              // }
              that.setData({
                picList: pic_list
              });
              wx.hideLoading();
              //wx.setStorageSync('imgs', upload_picture_list);
            }
          })
        }
        console.log(that.data.upload_picture_list);
        //显示
        // that.setData({
        //   upload_picture_list: pic_list,
        //   imgs: imgs
        // });
      }
    })

  },


  issueSaveOrSubmit(e) {
    let that = this
    console.log(e);


    if (e.detail.value.title == "") {
      wx.showToast({
        title: '请先输入标题',
        icon: 'none'
      })
      return;
    }

    // 点击添加图片的加号  就提交表单 创建Issue 返回issueId
    var btn = e.detail.target.dataset.btn;
    // 用户点击了保存按钮
    if (btn == "save") {
      that.createIssue(e, that.data.issueInfo.id, 'DRAFT');
      wx.switchTab({
        url: '../issueList/issueList',
        success: function(e) {
          var page = getCurrentPages().pop();
          if (page == undefined || page == null) return;
          page.onLoad();
        }
      })
    }
    // 点击提交按钮
    if (btn == "submit") {
      // 判断用户有没有上传图片的操作 如果上传了图片那么sourceId 有值。
      wx.showLoading({})
      that.createIssue(e, that.data.sourceId, 'OPEN'); //更新这个issue 发起流程 进入“分配”节点  

      wx.hideLoading();
      wx.switchTab({
        url: '../issueList/issueList',
        success: function(e) {
          var page = getCurrentPages().pop();
          if (page == undefined || page == null) return;
          page.onLoad();
        }
      })
    }
  },

  // 点击删除图片
  deleteImg(e) {
    let picList = this.data.picList;
    let index = e.currentTarget.dataset.index;
    console.log(index);
    wx.showToast({
      title: '删除中...',
    })
    var loginFlag = wx.getStorageSync('token');
    // var imageUrl = picList[index];
    // var imageId = imageUrl.substring(imageUrl.indexOf("=") + 1);
    // console.log(imageId)
    // 用索引获取list中图片对象  从对象中取出 上传图片时存入的imageId 然后用imageId 从数据库中删除图片。
    wx.request({
      url: path + "wx-com/image!deleteCmImage.action",
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        id: picList[index].imageId
      },
      success: function(res) {
        wx.hideToast();
      },
      fail: function(res) {
        console.log(res);
      }
    })
    picList.splice(index, 1);
    this.setData({
      picList: picList
    });
  },





  selectRole(e) {
    wx.navigateTo({
      url: '../createIssue/createRole',
    })
  },

  createIssue(e, issueId, lifecycleStatus) {
    var that = this;
    var data = that.data;
    var url = path + "wx-issue/q-iissue!createQIIssue.action";
    let loginFlag = wx.getStorageSync('token');
    var model = {};
    let o = e.detail.value;
    // var findWithAttr = that.findWithAttr(); //array, attr, value

    model.title = o.title;

    if (o.issueSourceId != null) {
      model.issueSourceId = data.issueSourceList[o.issueSourceId].id
    } else {
      model.issueSourceId = data.issueSourceList[that.findWithAttr(that.data.issueSourceList, "id", data.issueInfo.issueSourceId)].id
    }

    if (o.programId != null) {
      model.programId = data.programList[o.programId].id
    } else {
      model.programId = data.programList[that.findWithAttr(that.data.programList, "id", data.issueInfo.programId)].id
    } 

    if (o.programVehicleId != null) {
      model.programVehicleId = data.vehicleList[o.programVehicleId].id
    } else {
      model.programVehicleId = data.vehicleList[that.findWithAttr(that.data.vehicleList, "id", data.issueInfo.programVehicleId)].id
    } 

    if (o.partTypeId != null) {
      model.partTypeId = data.productTypeList[o.partTypeId].id
    } else {
      model.partTypeId = data.productTypeList[that.findWithAttr(data.productTypeList, "id", data.issueInfo.partTypeId)].id
    } 

    if (that.data.reportOrg != null && that.data.reportOrg != "") {
      model.reportOrg = data.reportOrg
    } else {
      model.reportOrg = data.issueInfo.reportOrg
    } 

    if (that.data.reportBy != null && that.data.reportBy != "") {
      model.reportBy = data.reportBy
    } else {
      model.reportBy = data.issueInfo.reportBy
    } 

    if (o.reportByName != null && o.reportByName != "") {
      model.reportByName = o.reportByName
    } else {
      model.reportByName = data.issueInfo.reportByName
    } 

    if (o.reportDate != null && o.reportDate != "") {
      model.reportDate = o.reportDate
    } else {
      model.reportDate = data.issueInfo.reportDate
    } 

    if (o.subPart != null && o.subPart != "") {
      model.subPart = o.subPart
    } else {
      model.subPart = data.issueInfo.subPart
    } 

    if (o.issueLevel != null && o.issueLevel != "") {
      model.issueLevel = data.issueLevelList[o.issueLevel].code;
    } else {
      model.issueLevel = data.issueInfo.issueLevel
    }

    if (o.issueTypeId != null && o.issueTypeId != "") {
      model.issueTypeId = data.issueTypeList[o.issueTypeId].id;
    } else {
      model.issueTypeId = data.issueInfo.issueTypeId
    }

    if (o.issueDescription != null && o.issueDescription != "") {
      model.issueDescription = o.issueDescription;
    } else {
      model.issueDescription = data.issueInfo.issueDescription
    }

    model.lifecycleStatus = lifecycleStatus; // 标识为草稿 不发起流程

    console.log(model);
    
    wx.request({
      url: url,
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        model: model,
        issueId: issueId
      },
      success: function(res) {
        console.log(res.data);
        var result = JSON.parse(res.data);
        that.setData({
          sourceId: result.data.issueId
        })
        console.log(that.data.sourceId);

      },
      error: function(res) {
        console.log(res);
      }
    })

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var data = that.data;
    var loginFlag = wx.getStorageSync('token');
    var issueId = options.issueId;
    var programVehicleId = options.programVehicleId;
    var issueInfo = null;
    var programList = null;
    var issueSourceList = null;
    var issueTypeList = null;
    // that.setData({
    //   date: currentDate
    // })

    var screenHeight = wx.getSystemInfoSync().windowHeight;
    const query = wx.createSelectorQuery();
    var album = query.select('album');

    // console.log(album);

    // const query = wx.createSelectorQuery();
    // query.select('.album')
    // this.ctx = wx.createCameraContext()
    // console.log(screenHeight);


    if (loginFlag) {


      //查询问题信息
      wx.request({
        url: path + 'wx-issue/q-iissue!getQIIssueInfo.action',
        header: {
          'token': loginFlag
        },
        data: {
          issueId: issueId
        },
        dataType: "JSON",
        success: function(res) {
          console.log(res);
          var result = JSON.parse(res.data);
          console.log(result.data);
          that.setData({
            issueInfo: result.data
          });

          // 查询项目列表
          wx.request({
            url: path + 'wx-pm/project-open-issue!getProgramList4RaiseIssue.action',

            header: {
              'token': loginFlag
            },
            dataType: "JSON",
            success: function(res) {

              var result = JSON.parse(res.data);

              that.setData({
                programList: result.data
              });
              var programIndex = that.findWithAttr(result.data, 'id', that.data.issueInfo.programId);

              that.setData({
                programIndex: programIndex // 页面picker 反显的项目索引
              })
            },
            fail: function(res) {
              console.log(res);
            }
          });



          wx.request({
            url: path + 'wx-pm/project-open-issue!getVehicleList4RaiseIssue.action',
            header: {
              'token': loginFlag,
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            dataType: "JSON",
            data: {
              programId: that.data.issueInfo.programId
            },
            success: function(res) {

              var result = JSON.parse(res.data);

              that.setData({
                vehicleList: result.data
              })
              var vehicleIndex = that.findWithAttr(result.data, 'id', that.data.issueInfo.programVehicleId);
              that.setData({
                vehicleIndex: vehicleIndex // 页面picker 显示的车型索引
              })

            },
            error: function(res) {
              console.log(res);
            }
          })

          // 根据项目中产品类别programTypes的值查询零件类别
          wx.request({
            url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',

            header: {
              'token': loginFlag
            },
            dataType: "JSON",
            data: {
              productTypes: that.data.issueInfo.productTypes
            },
            success: function(res) {

              var result = JSON.parse(res.data);
              that.setData({
                productTypeList: result.data
              })

              var productTypeIndex = that.findWithAttr(result.data, 'id', that.data.issueInfo.partTypeId);
              that.setData({
                productTypeIndex: productTypeIndex // 页面picker 显示的车型索引
              })
            },
            fail: function(res) {
              console.log(res);
            }
          })


          // 查询问题来源列表
          wx.request({
            url: path + 'wx-issue/q-iissue!getIssueSourceList.action',
            header: {
              'token': loginFlag
            },
            dataType: "JSON",
            success: function(res) {

              var result = JSON.parse(res.data);
              console.log(result.data);
              that.setData({
                issueSourceList: result.data
              });

              var idx = that.findWithAttr(result.data, 'id', that.data.issueInfo.issueSourceId);

               console.log(idx);
              that.setData({
                idx: idx // 页面picker 显示的车型索引
              })

              // console.log(that.data.issueSourceList);
            },
            fail: function(res) {
              console.log(res);
            }
          })

          //问题类型列表
          wx.request({
            url: path + 'wx-issue/q-iissue!getIssueTypeList.action',

            header: {
              'token': loginFlag
            },
            dataType: "JSON",
            //成功回调
            success: function(res) {

              var result = JSON.parse(res.data);

              that.setData({
                issueTypeList: result.data
              });
              var issueTypeIndex = that.findWithAttr(result.data, 'id', that.data.issueInfo.issueTypeId);
              console.log(issueTypeIndex);
              that.setData({
                issueTypeIndex: issueTypeIndex // 页面picker 显示的车型索引
              })
            },
            fail: function(res) {
              console.log(res);
            }
          });
    
          wx.request({
            url: path + 'wx-issue/q-iissue!getIssueLevelList.action',
            header: {
              'token': loginFlag
            },
            dataType: "JSON",
            success: function(res) {
    
              var result = JSON.parse(res.data);
              console.log(result.data);
              that.setData({
                issueLevelList: result.data
              });
            },
            fail: function(res) {
              console.log(res);
            }
          })
          
          wx.showLoading({
            title: '图片加载中...',
          })
          // 根据sourceId source 查询图片列表
          console.log("---------")

          console.log(data.issueInfo.issueId)
          wx.request({
            url: path + 'wx-com/image!selectCmImageList.action',
            header: {
              'token': loginFlag
            },
            data: {
              sourceId: that.data.issueInfo.id,
              source: 'QIM_ISSUE_IMAGE'
            },
            dataType: "JSON",

            success: function(res) {
              // console.log(res);
              var result = JSON.parse(res.data);
              var picIdList = result.data;
              var picList = [];

              for (var i = 0; i < picIdList.length; i++) {
                var img = {};
                img.imageId = picIdList[i].id;
                img.path = path + 'wx-com/image!downloadCmImage.action?id=' + picIdList[i].id;
                picList.push(img);

              }

              // console.log(result.data);
              that.setData({
                picList: picList,

              })
              wx.hideLoading();
            },
            fail: function() {
              console.log("fail");
            }
          })

        },
        fail: function() {
          console.log("fail");
        }
      });

    } else {
      // 无skey，作为首次登录
      wx.navigateTo({
        url: '../../login/login',
      })
    }

  },


  // 问题来源点击事件
  issueSourceChange: function(e) {
    this.setData({ //给变量赋值
      idx: e.detail.value
    })
  },
  // 车型点击事件
  vehicleChange: function(e) {
    this.setData({ //给变量赋值
      vehicleIndex: e.detail.value
    })
  },
  // 提出时间
  dateChange: function(e) {
    var that = this;
    var issueInfo = that.data.issueInfo;
    issueInfo.reportDate = e.detail.value;
    console.log(issueInfo)
    // var reportDate = 

    this.setData({
      issueInfo: issueInfo
    })
  },

  issueLevelListChange: function(e) {
    this.setData({
      issueLevelIndex: e.detail.value,
    })
  },
  // 问题类型Change事件
  issueTypeListChange: function(e) {
    this.setData({
      issueTypeIndex: e.detail.value,
    })
  },

  productTypeListChange: function(e) {

    this.setData({
      productTypeIndex: e.detail.value,
    })
  },
  //获取当前时间，格式YYYY-MM-DD
  getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },

  getVehicleList: function(programId) {
    var that = this;
    wx.request({
      url: path + 'wx-pm/project-open-issue!getVehicleList4RaiseIssue.action',
      header: {
        'token': loginFlag,
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      dataType: "JSON",
      data: {
        programId: programId
      },
      success: function(res) {

        var result = JSON.parse(res.data);

        that.setData({
          vehicleList: result.data
        })
      },
      error: function(res) {
        console.log(res);
      }
    })
  },

  // 项目点击事件
  programChange: function(e) {
    var that = this;

    that.setData({
      programIndex: e.detail.value,
    })

    let loginFlag = wx.getStorageSync('token');
    var programId = this.data.programList[this.data.programIndex].id;
    var productTypes = this.data.programList[this.data.programIndex].productTypes;
    console.log(productTypes);
    // 根据项目查询车型

    that.getVehicleList(programId);

    // 根据项目中产品类别programTypes的值查询零件类别
    wx.request({
      url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',

      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        productTypes: productTypes
      },
      success: function(res) {
        console.log(res.data);
        var result = JSON.parse(res.data);
        that.setData({
          productTypeList: result.data
        })
      },
      fail: function(res) {
        console.log(res);
      }
    })


  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})


/**
 * 上传图片方法
 */
function upload_file_server(url, that, tempFiles, i, sourceId, token) {
  //上传返回值
  console.log(tempFiles);
  const upload_task = wx.uploadFile({
    // 模拟https
    url: url, //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
    filePath: tempFiles[i].path, //上传的文件本地地址    
    name: 'upload',
    header: {
      'token': token
    },
    formData: {
      'num': i,
      'source': 'QIM_ISSUE_IMAGE',
      'sourceId': sourceId
    },
    //附近数据，这里为路径     
    success: function(res) {
      var data = JSON.parse(res.data);
      // //字符串转化为JSON  
      console.log("--------------");
      console.log(tempFiles);
      if (data.Success == true) {
        var filename = data.file //存储地址 显示
        tempFiles[i]['path_server'] = filename
      } else {
        tempFiles[i]['path_server'] = filename
      }
      that.setData({
        //  upload_picture_list: upload_picture_list
      });
      //wx.setStorageSync('imgs', upload_picture_list);
    }
  })
  //上传 进度方法
  upload_task.onProgressUpdate((res) => {
    console.log(res);
    console.log(res.progress);

    tempFiles[i]['upload_percent'] = res.progress
    that.setData({
      //  upload_picture_list: upload_picture_list
    });
  });

}